package com.knowledge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.knowledge.common.constant.GlobalConstant;
import com.knowledge.dao.entity.FriendEntity;
import com.knowledge.dao.entity.SysUser;
import com.knowledge.dao.mapper.FriendMapper;
import com.knowledge.service.FriendService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.knowledge.service.SysUserService;
import com.knowledge.vo.FriendVO;
import com.knowledge.vo.Result;
import com.knowledge.vo.params.PageParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 好友表（插入原则：user_id < friend_user_id） 服务实现类
 * </p>
 *
 * @author zzz
 * @since 2022-03-03
 */
@Service
public class FriendServiceImpl extends ServiceImpl<FriendMapper, FriendEntity> implements FriendService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public Result listFriendWithPage(SysUser user, PageParams pageParams) {
        if (pageParams == null){
            pageParams = new PageParams();
        }
        Page<FriendEntity> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
        QueryWrapper<FriendEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", user.getId()).or().eq("friend_user_id", user.getId());
        queryWrapper.orderByDesc("create_time");
        page = page(page, queryWrapper);
        List<FriendEntity> list = page.getRecords();
        List<Long> friendUserIds = new ArrayList<>();
        list.forEach(l->{
            if (l.getUserId().equals(user.getId())){
                friendUserIds.add(l.getFriendUserId());
            }else {
                friendUserIds.add(l.getUserId());
            }
        });
        //

        //关联用户信息
        List<FriendVO> friends = new ArrayList<>();
        if (friendUserIds.size() > 0){
           List<SysUser> userList = sysUserService.listByIds(friendUserIds);
            friends = userList.stream().map(u-> FriendVO.builder()
                    .friendUserId(u.getId())
                    .friendUserName(u.getNickname())
                    .friendAvatar(u.getAvatar())
                    .friendIsAdmin(u.getAdmin())
                    .meIsAdmin(user.getAdmin())
                    .build()).collect(Collectors.toList());
        }
        return Result.success(friends);
    }

    @Override
    public Boolean isFriend(Long userId1, Long userId2) {
        //查询是否好友
        FriendEntity params = convertFriendEntity(userId1, userId2);
        QueryWrapper<FriendEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", params.getUserId());
        queryWrapper.eq("friend_user_id", params.getFriendUserId());
        FriendEntity friendEntity = getOne(queryWrapper);
        return friendEntity == null ? false : true;
    }

    @Override
    public void addFriend(Long userId1, Long userId2) {
        if (!isFriend(userId1, userId2)){
            FriendEntity friendEntity = convertFriendEntity(userId1, userId2);
            friendEntity.setCreateTime(new Date());
            friendEntity.setUpdateTime(new Date());
            save(friendEntity);
        }
    }

    @Override
    public Boolean deleteFriend(Long userId1, Long userId2) {
        FriendEntity friendEntity = convertFriendEntity(userId1, userId2);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", friendEntity.getUserId());
        queryWrapper.eq("friend_user_id", friendEntity.getFriendUserId());
        return remove(queryWrapper);
    }

    @Override
    public Result searchFriend(Long userId, String account) {
        SysUser sysUser = sysUserService.findUserByAccount(account);
        FriendVO friendVO = null;
        if (sysUser != null){
            //搜索自己返回空
            if (!sysUser.getId().equals(userId)){
                //查询是否已经是好友
                Boolean isFriend = isFriend(userId, sysUser.getId());
                friendVO = FriendVO.builder().isFriend(isFriend ? GlobalConstant.YES : GlobalConstant.NO)
                        .friendUserName(sysUser.getNickname())
                        .friendUserId(sysUser.getId()).build();
            }
        }
        return Result.success(friendVO);
    }

    /**
    　* @description: 转换好友对象
    　* @param ${tags}
    　* @author zzz
    　* @date 2022/3/4 18:06
    */
    private FriendEntity convertFriendEntity(Long userId1, Long userId2){
        FriendEntity friendEntity = new FriendEntity();
        if (userId1 < userId2){
            friendEntity.setUserId(userId1);
            friendEntity.setFriendUserId(userId2);
        }else {
            friendEntity.setUserId(userId2);
            friendEntity.setFriendUserId(userId1);
        }
        return friendEntity;
    }
}
